<?php

namespace Admin\Controller;

use Utuo\BackgroundController;

class ModuleController extends BackgroundController {
	
	// 初始化
	public function _initialize() {
		$this->setControllerTitle('模块管理');
		$this->setActionTitle(array(
				'index' => '模块列表',
				'add' => '添加模块',
				'modify' => '修改模块',
				'recycle' => '回收站'
		));
		$this->setActionNav(array(
				'index',
				'add',
				'recycle'
		));
	}
	
	// 模块列表
	public function indexAction(){
		$this->getModuleList(0);
	}
	
	// 回收站
	public function recycleAction() {
		$this->getModuleList(1);
	}
	
	
	/**
	 * display the customer list
	 * @param unknown $is_deleted 是否已删除
	 */
	private function getModuleList($is_deleted) {
		$p = I("p", 1, 'intval');
		$condition = array(
			"is_deleted" => $is_deleted
		);
		$moduleLists = M("Module")->where($condition)->order("sort")->limit($this->getPageSize())->page($this->getPage())->select();
		$count =  M("Module")->where($condition)->count();
		$this->assign("moduleLists", $moduleLists);
		$this->showPage($count, $this->getPageSize());
		$this->display();
	}
	
	// 添加模块
	public function addAction() {
		$this->display();
	}
	
	// 提交添加
	public function addPostAction() {
		$d = M("Module");
		if ($d->create()) {
			if ($d->add()) {
				$this->ajaxSuccess();
			} else {
				$this->ajaxError();
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// 修改页
	public function modifyAction() {
		$module = $this->getOneById("Module");
		$this->assign("module", $module);
		$this->display();
	}
	
	// 修改提交
	public function modifyPostAction() {
		$d = D("Module");
		if ($d->create()) {
			if (false !== $d->save()) {
				$this->ajaxSuccess();
			} else {
				$this->ajaxError();
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// 移除模块
	public function removePostAction() {
		$this->ajaxRemove();
	}
	
	// 恢复模块
	public function restorePostAction() {
		$this->ajaxRestore();
	}
	
	// 删除模块
	public function deletePostAction() {
		$this->ajaxDelete();
	}
	
	// 状态更新
	public function setStatusPostAction() {
		$id = I("id", 0, "intval");
		$status = I("status", 0, "intval");
		$module = M("Module");
		if ($module->where("id={$id}")->setField("status", 1 - $status)) {
			$this->ajaxSuccess();
		} else {
			$this->ajaxError($module->getError());
		}
	}
	
	// 文件上传
	public function uploadAction() {
		$upload = new \Utuo\Upload();
		$info = $upload->uploadOne();
		if (!$info) {
			$this->ajaxError($upload->getError());
		}else{
			$this->ajaxSuccess("上传成功", $info);
		}
	}
	
}